# encoding=utf8

from flask import Blueprint, render_template, session

from . import sqlhelper
from .all import *
from .server_helper import *

__all__ = [
    'bp'
]

bp = Blueprint('dyb', __name__)


@bp.errorhandler(400)
def param_not_set(error):
    return return_fail(str(error))


@bp.errorhandler(404)
def page_not_found(error):
    return return_fail(str(error))


@bp.errorhandler(500)
def internal_server_error(error):
    return return_fail(str(error))


def _get_user():
    user = {}
    if 'username' in session:
        user["user"] = session["username"]
        user["nickname"] = session["username"]
    return M(user)


@bp.route('/', methods=['GET'])
@bp.route('/index.html', methods=['GET'])
def index():
    # return redirect(url_for('dyb.list_topic'))

    user = _get_user()

    # TODO 热门
    rs = sqlhelper.select_all("select * from t_topic order by indb desc limit 9")
    topics_group = group_every_size(rs, 3)
    last_group = topics_group[-1]
    if len(last_group) < 3:
        if len(last_group) <= 2:
            last_group.append({})

        if len(last_group) <= 1:
            last_group.append({})

    tpl = "index.html"
    return render_template(tpl, user=user, topics_group=topics_group)


@bp.route('/topic', methods=["GET"])
def list_topic(offset: int = 0):
    size = 10

    user = _get_user()

    topics = sqlhelper.select_all("select * from t_topic order by tid desc limit ? offset ?", (size, offset))
    next_offset = offset + size
    if len(topics) < size:
        next_offset = -1

    tpl = "list.html"
    return render_template(tpl, user=user, topics=topics, next=next_offset)


@bp.route('/topic/<int:tid>', methods=["GET"])
def show_topic(tid: int):
    user = _get_user()
    topic = sqlhelper.select_one("select * from t_topic where tid=? limit 1", (tid,))
    tpl = "topic.html"
    return render_template(tpl, user=user, topic=topic)
